<?php

namespace app\api\controller;


use app\api\model\User;
use app\BaseController;
use EasyWeChat\Factory;
use Firebase\JWT\JWT;
use think\App;
use think\exception\HttpResponseException;


/**
 * 登录控制器
 */
class Login extends BaseController
{
    private $factory;

    public function __construct(App $app)
    {
        parent::__construct($app);


        $config = [
            'app_id' => 'wx7a754d5410f8edfe',
            'secret' => 'd01a9640aa69b3ade7af3cfbd4f8ea8d',
            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
                'file' => __DIR__.'/wechat.log',
            ],
        ];

        $this->factory = Factory::miniProgram($config);
    }


    public function session()
    {
        $input = $this->_vali([
            'code.require'      => '授权code不能为空！',
        ],'POST');

        $rs = $this->curlGo([
            'url'=>'https://api.weixin.qq.com/sns/jscode2session',
            'data'=>[
                'appid'=> 'wx7a754d5410f8edfe',
                'secret'=> 'd01a9640aa69b3ade7af3cfbd4f8ea8d',
                'js_code'=> $input['code'],
                'grant_type'=>'authorization_code'
            ],
            'method'=>'get'
        ]);

        return json(['code'=>1,'data'=>$rs]);
    }

    /***
     * curl 请求
     * @param array $param
     * @return mixed
     */
    protected function curlGo($param = []){
        $url=$param['url'];
        $data=isset($param['data'])?$param['data']:[];
        $method=isset($param['method'])?$param['method']:'post';
        //初使化init方法
        $ch = curl_init();

        //指定URL
        curl_setopt($ch, CURLOPT_URL, $url);

        //设定请求后返回结果
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        if($method=='post'){
            //声明使用POST方式来进行发送  注释这个就是get请求
            curl_setopt($ch, CURLOPT_POST, 1);
        }

        //发送什么数据呢
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        //忽略证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        //忽略header头信息
        curl_setopt($ch, CURLOPT_HEADER, 0);

        //设置超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);

        //发送请求
        $output = curl_exec($ch);

        //关闭curl
        curl_close($ch);

        //返回数据
        return json_decode($output);
    }


    /**
     * 绑定手机号
     * @return \think\response\Json
     * @throws \WeChat\Exceptions\InvalidResponseException
     * @throws \WeChat\Exceptions\LocalCacheException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function phonelogin()
    {
        $input = $this->_vali([
            'session_key.require'      => '授权session_key不能为空！',
            'encryptedData.require'      => 'encryptedDataE不能为空！',
            'iv.require'      => '授权iv不能为空！',
        ],'POST');


        $decryptedData = $this->factory->encryptor->decryptData($input['session_key'], $input['iv'], $input['encryptedData']);

        if (isset($decryptedData['phoneNumber']) && $decryptedData['phoneNumber'] != '') {
            return $this->settoken($decryptedData['phoneNumber']);
        } else {
            return json(['code'=>0,'info'=>'信息授权失败']);
        }
    }

    public function settoken($phone) {
        $userid = User::where(['phone'=>$phone])
            ->value('id');

        if (!$userid) {
            $userid = User::mk()->insertGetId([
                'phone'=>$phone,
                'register_time' => time(),
                'login_time' => time()
            ]);
        }

        $user = User::where('id',$userid)->field('id,nickname')->find();

        // 验证token
        $time = time();
        $token = [
            'iat' => $time, //签发时间
            'nbf' => $time , //(Not Before)：某个时间点后才能访问，比如设置time+30，表示当前时间30秒后才能使用
            'exp' => time() + 3600 * 24 * 14, //过期时间
            'data' => [ //自定义信息，不要定义敏感信息
                'user_id' => $user['id'],
                'nickname' => $user['nickname'],
            ]
        ];

        $user['token'] = JWT::encode($token,"xiongshi");
        $user['logintime'] = time();

        return json(['code'=>1,'data'=>$user]);
    }
}